package com.yvan;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * Created by YuanHua on 2017/4/18.
 */
public class SortUtil {

    /**
     * 基本排序，适用于类型List<Map<String,Object>>并且Object extends Comparable
     *
     * @param list
     * @param key
     * @param sort
     * @param <T>
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static <T extends Comparable> void sort(List list, final String key, final String sort) {
        if (CollectionUtils.isEmpty(list) || StringUtils.isEmpty(key) || StringUtils.isEmpty(sort)) return;
        if (list.get(0) instanceof Map) {
            Collections.sort(list, new Comparator<Map>() {
                @Override
                public int compare(Map o1, Map o2) {
                    T val1 = (T) o1.get(key);
                    T val2 = (T) o2.get(key);
                    if (val1 == null || val2 == null) {
                        return 0;
                    }
                    if (sort.endsWith("desc")) {
                        return val1.compareTo(val2);
                    } else {
                        return val2.compareTo(val1);
                    }
                }
            });
        }
    }
}
